package com.agger.eurekaclientuserservice.controller;

import com.agger.eurekaclientuserservice.listener.ArticleReadListener;
import com.agger.eurekaclientuserservice.model.excelTemp.ArticleTemp;
import com.agger.eurekaclientuserservice.services.ArticleService;
import com.agger.eurekacommonapi.vo.ArticleVO;
import com.agger.eurekacommonapi.vo.PageResult;
import com.alibaba.excel.EasyExcel;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @classname: ExcelController
 * @description: Excel操作示例（EasyExcel https://www.yuque.com/easyexcel/doc/easyexcel）
 * @author chenhx
 * @date 2020-07-21 09:48:23
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {
    Logger log = LoggerFactory.getLogger(ExcelController.class);

    @Autowired
    private ArticleService service;

    @Autowired
    private DozerBeanMapper dozerMapper;     //类型转换器

    @Autowired
    private ApplicationContext applicationContext;



    /**
     * @Title: template
     * @Description: 下载Excel模板
     * @param 
     * @return void
     * @author chenhx
     * @date 2020-07-21 09:50:38
     */
    @GetMapping("/template")
    public void template(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("文章模板", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 根据ArticleVO类字段下载模板
        EasyExcel.write(response.getOutputStream(), ArticleTemp.class).sheet("模板").doWrite(new ArrayList());
        log.info("下载Excel模板成功...");
    }

    /**
     * @Title: upload
     * @Description: 上传Excel模板（根据上面下载的模板上传）
     * @param
     * @return void
     * @author chenhx
     * @date 2020-07-21 09:50:38
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        // 根据模板上传Excel，按照ArticleVO类读取，并存库
        EasyExcel.read(file.getInputStream(),ArticleTemp.class,new ArticleReadListener(service)).sheet()
                .headRowNumber(2)  // 指定表头行数，去除表头行数开始读。也可以不指定，自动根据ArticleTemp.class来解析，默认为1行
                .doRead();
        log.info("上传Excel模板成功...");
        return "success";
    }


    /**
     * @Title: download
     * @Description: 下载Excel
     * @param
     * @return void
     * @author chenhx
     * @date 2020-07-21 09:50:38
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response,@RequestBody(required = false) ArticleVO param) throws IOException {
        PageResult<ArticleVO> result = service.selectArticleList(param);
        if(result!=null&&result.getRows()!=null){
            // 将类型ArticleVO转换为ArticleTemp
            List<ArticleTemp> collect = result.getRows().stream().map(item -> dozerMapper.map(item, ArticleTemp.class)).collect(Collectors.toList());

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("文章数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 根据ArticleVO类字段下载模板
            // 真实环境应该将ExcelModel和VO分开传输和使用，不应该使用同一个bean
            EasyExcel.write(response.getOutputStream(), ArticleTemp.class).sheet("数据")
//                    .excludeColumnFiledNames();    //写排除字段集合，传入一个字段集合
//                    .includeColumnFiledNames();    //写包含字段集合，传入一个字段集合
                    .doWrite(collect);
        }
        log.info("下载Excel成功...");
    }

    /**
     * @Title: download
     * @Description: 下载Excel 填充模板数据
     * @param
     * @return void
     * @author chenhx
     * @date 2020-07-21 09:50:38
     */
    @GetMapping("/downloadFill")
    public void downloadFill(HttpServletResponse response,@RequestBody(required = false) ArticleVO param) throws IOException {
        PageResult<ArticleVO> result = service.selectArticleList(param);
        if(result!=null&&result.getRows()!=null){
            // 将类型ArticleVO转换为ArticleTemp
            List<ArticleTemp> collect = result.getRows().stream().map(item -> dozerMapper.map(item, ArticleTemp.class)).collect(Collectors.toList());

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("填充文章数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 根据ArticleVO类字段下载模板
            // 真实环境应该将ExcelModel和VO分开传输和使用，不应该使用同一个bean
            String path = ExcelController.class.getResource("/").getPath() + "/template/填充模板.xlsx";

//            String path = Thread.currentThread().getContextClassLoader().getResource("") + "template/填充模板.xlsx";

            Resource resource = applicationContext.getResource("classpath:template/填充模板.xlsx");
            InputStream inputStream = resource.getInputStream();

            EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).sheet().doFill(collect);

        }
        log.info("下载Excel成功...");
    }





}
